<?php
namespace app\shop\model;

use app\BaseModel;
use app\integral\model\Integral;
use app\member\model\DiscountGoods;
use app\shop\controller\Discount;
use app\shop\controller\DoDiscount;
use app\shop\controller\DoMinus;
use app\shop\controller\IndexShopGoods;
use app\shop\server\DoAtv;
use think\facade\Db;


class IndexShopOrderGoods extends BaseModel
{
    //定义表名
    protected $name = 'longbing_card_shop_order_item';

    //初始化

    /**
     *
     * 获取自订单详情
     */
    public function orderGoodsInfo($dis){
        $data = $this
            ->alias('a')
            ->leftJoin('longbing_card_goods b' ,'a.goods_id = b.id')
            ->where($dis)
            ->field(['a.*,b.id,b.unit,b.is_self'])
            ->order('a.id desc')
            ->select()
            ->toArray();
        $data = transImages($data,['cover']);
        return $data;
    }


    /**
     * @param $dis
     * @return float
     * 获取商品件数
     */
    public function getGoodsNum($dis){
        $data = $this->where($dis)->sum('number');
        return $data;

    }


    /**
     * @param $data
     * 添加子订单
     */
    public function orderGoodsAdd($data){

        $data['create_time'] = time();

        $data['update_time'] = time();

        $res = $this->insert($data);


        return $res;

    }
    /**
     * @param $dis
     * @return float
     * 获取历史商品件数
     */
    public function getGoodsNumber($dis){
        //取消订单的不算 chen
        $num = $this->alias('a')
                ->join('longbing_card_shop_order b','a.order_id = b.id')
                ->where($dis)
                ->where('b.order_status','<>',1)
                ->where('a.integral_id','=',0)
                ->where('b.refund_status','<>',2)
                ->where('b.type','<>',1)
                ->group('a.id')
                ->sum('a.number');

        return $num;

    }


    /**
     * @author chenniang
     * @DataTime: 2020-08-03 14:19
     * @功能说明:检查订单
     */
    public function checkOrder($input,$spe,$value,$user_id,$goods){

        $lastOrder = $this->getGoodsNumber(['a.goods_id'=>$value['goods_id'],'b.user_id'=>$user_id] );

        if(empty($input['collage_id'])&&empty($input['bargain_id'])&&empty($input['integral_id'])) {

            if ($goods['is_limit'] == 2 && $lastOrder + $value['number'] > $goods['limit']) {

                return ['code'=>400,'msg' => '超出限购数量'];

            }

            if ($value['number'] < $goods['start_min']) {

                return ['code'=>400,'msg' => '起购数量为' . $goods['start_min']];

            }

        }
        if($spe['stock']<$value['number']){

            return ['code'=>400,'msg' => '库存不足'];
        }

        if($value['number']<=0){

            return ['code'=>400,'msg' => '商品数量有误'];
        }

        if(empty($goods)||empty($spe)){

            return ['code'=>400,'msg' => '商品信息未找到'];

        }

        $spe_price_model = new IndexShopSpePrice();

        $goods_model     = new IndexGoods();

        $car_model       = new IndexShopCar();

        $num = $value['number'];
        //减库存
        $res = $spe_price_model->spePriceUpdate(['id'=>$value[ 'spe_price_id' ],'stock'=>$spe['stock'],'create_time'=>$spe['create_time']],['stock'=>Db::raw("stock-$num"),'create_time'=>$spe['create_time']+1]);

        if($res!=1){

            return ['code'=>400,'msg' => '下单人数过多，请重新下单'];

        }
        //加销量
        $res = $goods_model->goodsUpdate(['id'=>$value[ 'goods_id' ],'sale_count'=>$goods['sale_count']],['sale_count'=>Db::raw("sale_count+$num")]);

        if($res!=1){

            return ['code'=>400,'msg' => '下单人数过多，请重新下单'];
        }

        $car_model->carUpdate(['spe_price_id'=>$value['spe_price_id'],'goods_id'=>$value['goods_id'],'user_id'=>$user_id],['status'=>-1]);//删除购物车

        return ['code'=>200,'msg' => ''];

    }


    /**
     * @author chenniang
     * @DataTime: 2022-01-21 14:32
     * @功能说明:下单时候的各种活动
     *
     * 使用策略模式 ，下面最多有且只有一个模型会执行
     */
    public function payOrderInfoAtv($input,$spe,$goods){

        if((!empty($input['is_integral'])||empty($input['buy_limit']))&&empty($input['collage_id'])&&empty($input['collage_id'])){
            //使用积分活动
            $model = new Integral();

        }elseif(!empty($input['collage_id'])){
            //拼团
            $model = new IndexShopCollageList();

        }else if(!empty($input['bargain_id'])){
            //砍价
            $model = new BargainRecord();
        }

        if(!empty($model)){

            $atv_model = new DoAtv();

            $atv_model->addObserver($model);

            $data = $atv_model->notify($input,$spe,$goods);

        }

        if(!empty($data['code'])){

            return $data;
        }

        $data['spe']   = !empty($data['spe'])?$data['spe']:$spe;

        $data['goods'] = !empty($data['goods'])?$data['goods']:$goods;

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-01-30 16:14
     * @功能说明:订单折扣 订单的所有关于折扣的都在这里处理
     */
    public function orderGoodsDiscount($goods,$user_id,$uniacid,$value,$input,$discount_add=1){

        $discount_goods_model = new DiscountGoods();

        $wholesale_model      = new GoodsWholesale();
        //是不是会员商品
        $is_member = $discount_goods_model->isMember($goods['is_member'],$uniacid);
        //会员商品不享受折扣
        if($is_member==0&&empty($input['bargain_id'])&&empty($input['collage_id'])&&$discount_add==1){

            $where=[

                'goods_id'=> $value['goods_id'],

                'spe_id'  => $value['spe_price_id'],

                'number'  => $value['number'],

                'uniacid' => $uniacid,

                'user_id' => $user_id,

               // 'integral_id' => $input['integral_id'],
            ];

            $discount_server = new \app\shop\server\Discount();
            //会员折扣
            $discount_server->addObserver($discount_goods_model);

            if(empty($input['is_integral'])){
                //批发价折扣
                $discount_server->addObserver($wholesale_model);
            }
            //观察模式获取折扣最低的打折方式
            $arr_discount = $discount_server->notify($where);

            $arr = $arr_discount[0];

        }

        $data['is_member']       = $is_member;
        //会员折扣
        $data['member_discount'] = isset($arr['member_discount'])?$arr['member_discount']:1;
        //是否是会员折扣商品
        $data['is_goods_member'] = isset($arr['is_goods_member'])?$arr['is_goods_member']:0;
        //批发价折扣
        $data['sale_discount']   = isset($arr['sale_discount'])?$arr['sale_discount']:1;
        //批发价id
        $data['sale_id']         = isset($arr['sale_id'])?$arr['sale_id']:0;

        return $data;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-01 15:39
     * @功能说明:处理折扣信息
     */
    public function doDiscount($discount_data,$order_goods_id){

        $sale_discount   = new WholesaleOrder();

        $discount_server = new \app\shop\server\DoDiscount();

        $integral        = new \app\member\model\Integral();
        //会员折扣
        $discount_server->addObserver($sale_discount);
        //积分抵扣
        $discount_server->addObserver($integral);
        //观察模式获取折扣最低的打折方式
        $discount_server->notify($discount_data,$order_goods_id);

        return true;
    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-01 16:13
     * @功能说明:处理营销活动
     */
    public function doMinusAtv($input,$order_id,$goods,$number,$user_id,$spe){

        $input['order_id']   = $order_id;

        $input['goods_info'] = $goods;

        $input['number']     = $number;

        $input['user_id']    = $user_id;

        $input['spe']        = $spe;

        $collage_model   = new IndexShopCollageList();

        $bargain_model   = new BargainRecord();

        $discount_server = new \app\shop\server\DoMinus();
        //使用积分活动
        $integral_model  = new Integral();
        //拼团
        $discount_server->addObserver($collage_model);
        //砍价
        $discount_server->addObserver($bargain_model);
        //积分
        $discount_server->addObserver($integral_model);

        $minus_arr = $discount_server->notify($input);

        if(!empty($minus_arr['code'])){

            return $minus_arr;
        }

        $minus_arr['spe_name_text'] = isset($minus_arr['spe_name'])?$minus_arr['spe_name']:$spe['spe_name_text'];

        $minus_arr['name']          = isset($minus_arr['goods_name'])?$minus_arr['goods_name']:$goods['name'];

        $minus_arr['cover']         = isset($minus_arr['goods_cover'])?$minus_arr['goods_cover']: $goods['cover'];

        $minus_arr['type']          = isset($minus_arr['collage_type'])?1:0;

        $minus_arr['collage_id']    = isset($minus_arr['collage_id'])?$minus_arr['collage_id']:0;

        $minus_arr['goods_price']   = $spe['price'];

        $minus_arr['price']         = isset($minus_arr['price'])?$minus_arr['price']:$spe['price'];

        $minus_arr['integral']      = isset($minus_arr['integral'])?$minus_arr['integral']:0;

        $minus_arr['integral_atv_id'] = isset($minus_arr['integral_atv_id'])?$minus_arr['integral_atv_id']:0;

        $minus_arr['i_record_id'] = isset($minus_arr['i_record_id'])?$minus_arr['i_record_id']:0;
        //积分抵扣多少钱
        $minus_arr['i_price']     = isset($minus_arr['i_price'])?$minus_arr['i_price']:0;

        $minus_arr['integral_goods_id'] = isset($minus_arr['integral_goods_id'])?$minus_arr['integral_goods_id']:0;

        return $minus_arr;

    }


    /**
     * @author chenniang
     * @DataTime: 2021-02-02 11:22
     * @功能说明:获取商品的配送方式
     */
    public function getGoodsSend($goods_info){

        $goods_model = new IndexGoods();

        $data = [

            'is_self' => 0,

            'is_send' => 0,
        ];

        foreach ($goods_info as $value){
            //商品信息
            $goods   = $goods_model->goodsInfo(['id'=>$value['goods_id']]);

            if($goods['is_self']==1){

                $data['is_self'] = 1;
            }

            if($goods['is_send']==1){

                $data['is_send'] = 1;
            }

        }

        return $data;

    }





}